﻿using CurrentUserDemo.Domain.CurrentUsers;
using DotNetCore.CAP;

namespace CurrentUserDemo.Api.Extensions
{
    public static class CapPublishExtensions
    {
        public static void PublishEvent<T>(this ICapPublisher capPublisher, string name, T? contentObj, IDictionary<string, string?> headers)
        {
            headers = SetUserId(capPublisher, headers);
            capPublisher.Publish(name, contentObj, headers);
        }

        public static async Task PublishEventAsync<T>(this ICapPublisher capPublisher, string name, T? contentObj, IDictionary<string, string?> headers, CancellationToken cancellationToken = default)
        {
            headers = SetUserId(capPublisher, headers);
            await capPublisher.PublishAsync(name, contentObj, headers, cancellationToken);
        }

        public static void PublishDelayEvent<T>(this ICapPublisher capPublisher, TimeSpan delayTime, string name, T? contentObj, IDictionary<string, string?> headers)
        {
            headers = SetUserId(capPublisher, headers);
            capPublisher.PublishDelay(delayTime, name, contentObj, headers);
        }

        public static async Task PublishDelayEventAsync<T>(this ICapPublisher capPublisher, TimeSpan delayTime, string name, T? contentObj, IDictionary<string, string?> headers, CancellationToken cancellationToken = default)
        {
            headers = SetUserId(capPublisher, headers);
            await capPublisher.PublishDelayAsync(delayTime, name, contentObj, headers, cancellationToken);
        }

        private static IDictionary<string, string?> SetUserId(ICapPublisher capPublisher, IDictionary<string, string?> headers)
        {
            var currentUser = capPublisher.ServiceProvider.CreateScope().ServiceProvider.GetService<ICurrentUser>();
            headers ??= new Dictionary<string, string?>();

            if (!headers.ContainsKey("my.header.uid"))
            {
                headers.Add("my.header.uid", currentUser!.GetUserId().ToString());
            }

            return headers;
        }
    }
}
